package org.openkanban.server.service.impl;

import org.apache.commons.lang.StringUtils;
import org.openkanban.server.dao.UserDao;
import org.openkanban.server.domain.User;
import org.openkanban.server.service.UserService;
import org.openkanban.shared.util.StatusCodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * standard service implementation of {@code UserService}
 */
@Service
public class UserServiceDefaultImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User signUp(User user) {
	return userDao.createUser(user);
    }

    @Override
    public boolean logIn(User user) {
	return userDao.authentificate(user);
    }

    @Override
    public StatusCodes addContact(String parentUserId, String eMail) {
	return userDao.addContact(parentUserId, eMail);
    }

    @Override
    public StatusCodes removeContact(User user, String eMail) {
	return userDao.removeContact(user, eMail);
    }

    @Override
    public User getUser(Long userId) {
	return userDao.getUser(userId);
    }

    @Override
    public User[] getContacts(Long userId) {
	return userDao.getContacts(userId);
    }

    @Override
    @Transactional
    public StatusCodes updateUser(User user) {
	User userToUpdate = userDao.getUser(user.getUserId());
	userToUpdate.setVorname(user.getVorname());
	userToUpdate.setNachname(user.getNachname());
	userToUpdate.setNamensKuerzel(user.getNamensKuerzel());
	userToUpdate.setEmail(user.getEmail());
	return userDao.updateUser(userToUpdate);
    }

    @Override
    @Transactional
    public StatusCodes updatePassword(Long userId, String oldPassword, String newPassword) {
	User user = userDao.getUser(userId);
	if (!StringUtils.isEmpty(oldPassword) && oldPassword.equals(user.getPassword())) {
	    user.setPassword(newPassword);
	    return userDao.updateUser(user);
	}
	return StatusCodes.INVALID_INPUT_DATA;
    }

    @Override
    public StatusCodes updateAvatar(Long userId, String avatarUrl) {
	User user = userDao.getUser(userId);
	user.setAvatarUrl(avatarUrl);
	return userDao.updateUser(user);
    }
}
